<?php

namespace app\api\controller;

use think\Controller;
use think\Db;

class AuthController extends Controller
{
    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @Date 2018年11月30日
     * @Author Eric <ieyangxiaoguo@126.com>
     */
    public function onLogin(){
        $code = $this->request->param('code','');
        $AppID = '';
        $AppSecret = '';
        if ($code) {
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$AppID.'&secret='.$AppSecret.'&js_code='.$code.'&grant_type=authorization_code';
            
            //初始化curl
            $ch = curl_init();
            //设置超时
            //curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            //运行curl，结果以json形式返回
            $result = curl_exec($ch);
            
            curl_close($ch);
            $result= json_decode($result,true);
            
            $res['result'] = $result;

            $find = Db::name('user')->where('openid',$result['openid'])->find();
            if ($find) {
                $uid = $find['id'];
            }else{
                $data = [
                    'openid' => $result['openid'],
                    'subscribe_time' => time()
                ];
                
                $uid = Db::name('user')->insertGetId($data);
            }
            
            $res['uid'] = $uid;
        }else{
            $res['code'] = 0;
            $res['msg'] = '未获取到code';
        }
        
        return $res;
    }
}
